package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {

        //--1--和微信服务进行交互（HttpClient）
        Map<String,String> paramMap=new HashMap<>();
        paramMap.put("appid",weChatProperties.getAppid());      //Id
        paramMap.put("secret",weChatProperties.getSecret());    //密钥
        paramMap.put("js_code",userLoginDTO.getCode());         //登录时获取的 code
        paramMap.put("grant_type","authorization_code"); //固定值authorization_code

        //--2--发送get请求，和微信服务端通信    HTTPS 调用 -> GET
        String wechatURL="https://api.weixin.qq.com/sns/jscode2session";
        String result = HttpClientUtil.doGet(wechatURL, paramMap);

        JSONObject jsonObject = JSONObject.parseObject(result);    //Json字符串转java对象
        String openid = jsonObject.getString("openid");       //面向对象思想，获取数据

        //--3--验证：openid（用户唯一标识）是否存在
        if(openid==null){
            throw new LoginFailedException("登录失败，无效微信用户");
        }

        //--4--判断当前openid是否是新用户
        User user=userMapper.selectByOpenId(openid);

        if (user==null){
            //新用户：注册（添加到用户表）
            user=User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);     //主键返回********
        }

        //--5--携带Id的user对象
        return user;
    }
}
